﻿using Microsoft.Web.Administration;
using QuickManager.Code.SiteMgr.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.DirectoryServices;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace QuickManager.Code.SiteMgr
{
    public class IISMenager
    {
        public static string ErrorMessage { set; get; }

        #region 新建立一个IISWEB站点

        ///<summary>
        ///添加一个站点
        ///</summary>
        public static bool CreateWebSite(SiteInfoModel siteInfo)
        {
            //
            ServerManager svrMgr = new ServerManager();
            Site site = null;
            int port = 80;
            int.TryParse(siteInfo.Port, out port);
            if (svrMgr.Sites.ToList().Exists(m => m.Name == siteInfo.SiteName))
            {
                DeleteWebSite(siteInfo.SiteName);
                svrMgr = new ServerManager();
            }
            ApplicationPool appPool = CreateAppPool(siteInfo);
            svrMgr = new ServerManager();
            site = svrMgr.Sites.Add(siteInfo.SiteName, siteInfo.LocalPath, port);

            //应用程序池
            site.ApplicationDefaults.ApplicationPoolName = appPool.Name;

            svrMgr.CommitChanges();

            //
            return true;
        }

        public static void DeleteWebSite(string siteName)
        {
            ServerManager SvrMgr;
            Site site = null;
            ApplicationPool appPool = null;
            string appPoolName = string.Empty;
            try
            {
                //删除旧的站点和应用程序池
                SvrMgr = new ServerManager();
                site = SvrMgr.Sites.FirstOrDefault<Site>(m => m.Name == siteName);
                if (site != null)
                {
                    appPoolName = site.ApplicationDefaults.ApplicationPoolName;
                    if (appPool != null)
                    {
                        appPoolName = appPool.Name;
                    }
                    SvrMgr.Sites.Remove(site);
                    SvrMgr.CommitChanges();
                }
            }
            catch
            {
            }

            try
            {
                //删除应用程序池
                if (!string.IsNullOrEmpty(appPoolName))
                {
                    SvrMgr = new ServerManager();
                    appPool = SvrMgr.ApplicationPools.FirstOrDefault(m => m.Name == site.ApplicationDefaults.ApplicationPoolName);
                    SvrMgr.ApplicationPools.Remove(appPool);
                    SvrMgr.CommitChanges();
                }
            }
            catch
            {
            }
        }

        public static ApplicationPool CreateAppPool(SiteInfoModel siteInfo)
        {
            ServerManager SvrMgr = new ServerManager();
            try
            {
                string appPoolName = siteInfo.SiteName; //应用程序池名称
                ApplicationPool appPool = null;
                if (SvrMgr.ApplicationPools.ToList().Exists(m => m.Name == appPoolName))
                {
                    appPool = SvrMgr.ApplicationPools.FirstOrDefault(m => m.Name == appPoolName);
                }
                else
                {
                    appPool = SvrMgr.ApplicationPools.Add(appPoolName);
                }
                //应用程序池设置
                switch (siteInfo.NetVersion)
                {
                    case ".NET 1.1":
                        {
                            appPool.ManagedRuntimeVersion = "v1.1";
                            break;
                        }
                    case ".NET 2.0":
                        {
                            appPool.ManagedRuntimeVersion = "v2.0";
                            break;
                        }
                    case ".NET 4.0":
                        {
                            appPool.ManagedRuntimeVersion = "v4.0";
                            break;
                        }
                }
                //运行模式
                switch (siteInfo.PoolType)
                {
                    case "经典模式":
                        {
                            //托管模式Integrated为集成 Classic为经典
                            appPool.ManagedPipelineMode = ManagedPipelineMode.Classic;
                            break;
                        }
                    default:
                        {
                            appPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
                            break;
                        }
                }
                //ping设置
                appPool.ProcessModel.PingingEnabled = false;

                //提交改变
                SvrMgr.CommitChanges();

                return appPool;
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.ToString();
                return null;
            }
        }

        /// <summary>
        /// 回收应用程序池
        /// </summary>
        /// <param name="siteName"></param>
        public static void DisposeAppPool(string siteName)
        {
            ServerManager SvrMgr = new ServerManager();
            string appName = SvrMgr.Sites.FirstOrDefault(m => m.Name == siteName).ApplicationDefaults.ApplicationPoolName;
            SvrMgr.ApplicationPools.FirstOrDefault(m => m.Name == appName).Recycle();
            SvrMgr.CommitChanges();
        }

        public static void ResetIIS()
        {
            Process.Start("iisreset");
        }

        /// <summary>
        /// 启动网站
        /// </summary>
        /// <param name="siteName"></param>
        /// <returns></returns>
        public static void StartWebSite(string siteName)
        {
            ServerManager SvrMgr = new ServerManager();
            Site site = SvrMgr.Sites.FirstOrDefault(m => m.Name == siteName);
            ApplicationPool pool = SvrMgr.ApplicationPools.FirstOrDefault(m => m.Name == site.ApplicationDefaults.ApplicationPoolName);

            if (site.State == ObjectState.Stopped)
            {
                string port = IISMenager.GetDefaultPort(site);
                foreach (var item in SvrMgr.Sites)
                {
                    if (item.State != ObjectState.Started && port == IISMenager.GetDefaultPort(item))
                    {
                        item.Stop();
                        var p = SvrMgr.ApplicationPools.FirstOrDefault(m => m.Name == site.ApplicationDefaults.ApplicationPoolName);
                        if (p != null && p.State != ObjectState.Stopped)
                        {
                            p.Start();
                        }
                    }
                }
                site.Start();
            }
            if (pool.State == ObjectState.Stopped)
            {
                pool.Start();
            }
        }

        public static void StopWebSite(string siteName)
        {
            ServerManager SvrMgr = new ServerManager();
            Site site = SvrMgr.Sites.FirstOrDefault(m => m.Name == siteName);
            ApplicationPool pool = SvrMgr.ApplicationPools.FirstOrDefault(m => m.Name == site.ApplicationDefaults.ApplicationPoolName);
            if (site.State == ObjectState.Started)
            {
                site.Stop();
            }
            if (pool.State == ObjectState.Started)
            {
                pool.Stop();
            }
        }

        public static string GetWebSiteState(string siteName)
        {
            ServerManager SvrMgr = new ServerManager();
            try
            {
                ObjectState state = SvrMgr.Sites.FirstOrDefault(m => m.Name == siteName).State;
                switch (state)
                {
                    case ObjectState.Started:
                        {
                            return "运行中";
                        }
                    case ObjectState.Starting:
                    case ObjectState.Stopped:
                    case ObjectState.Stopping:
                        {
                            return "未运行";
                        }
                    default:
                        {
                            return "未知";
                        }
                }
            }
            catch
            {
                return "未知";
            }
        }

        public static string GetPhysicalPath(Site site)
        {
            return site.Applications.FirstOrDefault().VirtualDirectories.FirstOrDefault().PhysicalPath;
        }

        public static string GetDefaultPort(Site site)
        {
            try
            {
                string[] parts = site.Bindings.FirstOrDefault().Attributes["bindingInformation"].Value.ToString().Split(':');
                return parts[parts.Length - 2];
            }
            catch
            {
                return string.Empty;
            }
        }

        public static string GetPoolType(Site site)
        {
            ServerManager SvrMgr = new ServerManager();
            try
            {
                if (SvrMgr.ApplicationPools
                    .FirstOrDefault(m => m.Name == site.ApplicationDefaults.ApplicationPoolName).ManagedPipelineMode == ManagedPipelineMode.Classic)
                {
                    return "经典模式";
                }
                else
                {
                    return "集成模式";
                }
            }
            catch
            {
                return "集成模式";
            }
        }

        public static string GetNetVersion(Site site)
        {
            ServerManager SvrMgr = new ServerManager();
            ApplicationPool appPool = SvrMgr.ApplicationPools
                        .FirstOrDefault(m => m.Name == site.ApplicationDefaults.ApplicationPoolName);
            if (appPool==null)
            {
                return string.Empty;
            }
            if (Regex.IsMatch(appPool.ManagedRuntimeVersion, "v1.1"))
            {
                return ".NET 1.1";
            }
            else if (Regex.IsMatch(appPool.ManagedRuntimeVersion, "v4.0"))
            {
                return ".NET 4.0";
            }
            else
            {
                return ".NET 2.0";
            }
        }


        #endregion
    }
}
